package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
@Slf4j
//@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {
    //@Autowired
    //private RestTemplate restTemplate;
    //    @Autowired
//    private RibbonLoadBalancerClient client;
    //private DiscoveryClient discoveryClient;

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        //String url = "http://user-service/user/" + id;
        //String user = restTemplate.getForObject(url,String.class);
        return userClient.queryById(id);
    }





/*    //@HystrixCommand(fallbackMethod = "queryByIdFallback") //失败容错的指令，开启线程隔离的服务降级,成功和失败的方法返回值、参数列表必须完全一样
    //@HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000")})//设置超时时长
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60")
    })
    public String queryById(@PathVariable("id") Long id){
        if(id % 2 == 0){
            throw new RuntimeException("");
        }
        String url = "http://user-service/user/" + id;
        String user = restTemplate.getForObject(url,String.class);
        return user;
    }
    public String queryByIdFallback(Long id){
        log.error("查询用户信息失败：id:{}" ,id);
        return "不好意思，服务器太拥挤了！";
    }
    public String defaultFallback(){
        log.error("查询用户信息失败：id:{}");
        return "不好意思，服务器太拥挤了！";
    }*/





/*    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        //根据服务id获取实例
        //List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //从实例中取出ip和端口
//        ServiceInstance instance = instances.get(0);

        //随机、轮询、hash
//        ServiceInstance instance1 = client.choose("user-service");//默认轮询
//        String host = instance1.getHost() + ":" + instance1.getPort();

       // String url = "http://" + host + "/user/" + id;
        String url = "http://user-service/user/" + id;
        User user = restTemplate.getForObject(url,User.class);
        return user;
    }*/
}
